import { NextResponse } from 'next/server'
import fs from 'fs'
import path from 'path'

export async function POST() {
  try {
    const sourcePath = path.join(process.cwd(), 'prisma/dev.db')
    const dateStr = new Date().toISOString().split('T')[0]
    const destPath = path.join(process.cwd(), 'prisma', `${dateStr}.db`)
    
    // 检查源文件是否存在
    if (!fs.existsSync(sourcePath)) {
      return NextResponse.json(
        { error: 'Source database file not found' },
        { status: 404 }
      )
    }
    
    // 复制文件
    fs.copyFileSync(sourcePath, destPath)
    
    const fileBuffer = fs.readFileSync(destPath)
    const headers = new Headers()
    headers.set('Content-Type', 'application/octet-stream')
    headers.set('Content-Disposition', `attachment; filename="${dateStr}.db"`)
    
    const response = new NextResponse(fileBuffer, {
      status: 200,
      headers
    })
    
    // 下载完成后删除临时文件
    fs.unlinkSync(destPath)
    
    return response
  } catch (error) {
    console.error('Backup failed:', error)
    return NextResponse.json(
      { error: 'Failed to backup database' },
      { status: 500 }
    )
  }
}